package io.renren.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.GeneralSecurityException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.taobao.api.Constants;
import com.taobao.api.internal.util.StringUtils;

import io.renren.common.constans.TaoBaoUrlConstans;

/**
 * 从淘宝获取数据
 * @author 朝乐门
 *
 */
public class TaobaoAPISignUtil {
	
	public static PropertyUtil propertyUtil = PropertyUtil.getInstance();
	
	public static String signTopRequest(Map<String, String> params, String secret, String signMethod)
			throws IOException {
		// 第一步：检查参数是否已经排序
		String[] keys = params.keySet().toArray(new String[0]);
		Arrays.sort(keys);
		// 第二步：把所有参数名和参数值串在一起
		StringBuilder query = new StringBuilder();
		if (Constants.SIGN_METHOD_MD5.equals(signMethod)) {
			query.append(secret);
		}
		for (String key : keys) {
			String value = params.get(key);
			if (StringUtils.areNotEmpty(key, value)) {
				query.append(key).append(value);
			}
		}
		// 第三步：使用MD5/HMAC加密
		byte[] bytes = encryptHMAC(query.toString(), secret);
		return byte2hex(bytes);
	}

	public static byte[] encryptHMAC(String data, String secret) throws IOException {
		byte[] bytes = null;
		try {
			SecretKey secretKey = new SecretKeySpec(secret.getBytes(Constants.CHARSET_UTF8), "HmacMD5");
			Mac mac = Mac.getInstance(secretKey.getAlgorithm());
			mac.init(secretKey);
			bytes = mac.doFinal(data.getBytes(Constants.CHARSET_UTF8));
		} catch (GeneralSecurityException gse) {
			throw new IOException(gse.toString());
		}
		return bytes;
	}

	public static String byte2hex(byte[] bytes) {
		StringBuilder sign = new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(bytes[i] & 0xFF);
			if (hex.length() == 1) {
				sign.append("0");
			}
			sign.append(hex.toUpperCase());
		}
		return sign.toString();
	}
	
	/**
	 * 获得淘宝返回的json信息
	 * @author 朝乐门
	 * @param params (不用传sign)
	 * @return
	 * @throws IOException 
	 */
	public static String getResult(Map<String, String> params) {
		String sign = new String();
		String result = new String();
		try{
			sign = TaobaoAPISignUtil.signTopRequest(params, propertyUtil.getValue("secret"), propertyUtil.getValue("signMethod"));
			params.put("sign", sign);
			System.out.println("------------"+getUrl(params));
			HttpClient client =  HttpClients.custom().build();
			HttpGet httpget = new HttpGet(getUrl(params));
			HttpResponse response = client.execute(httpget);  
			if(response.getStatusLine().getStatusCode() == 200)  
			{  
				BufferedReader br=null;
				InputStream input = null;
				try {
					HttpEntity httpEntity = response.getEntity();  
					//从消息载体对象中获取操作的读取流对象  
					input=httpEntity.getContent();  
					br=new BufferedReader(new InputStreamReader(input));  
					result=br.readLine();  
					
				} catch (Exception e) {
					e.printStackTrace();
				}finally{
					
					if(br != null){
						br.close();  
					}
					if(input != null){
						input.close(); 
					}
				}
			} 
		}catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	private static String getUrl(Map<String, String> params) throws UnsupportedEncodingException {
		StringBuffer sb = new StringBuffer(propertyUtil.getValue("baseUrl"));
		for(String key : params.keySet()){
			sb.append(URLEncoder.encode(key,Constants.CHARSET_UTF8)+"="+URLEncoder.encode(params.get(key), Constants.CHARSET_UTF8)+"&");
		}
		return sb.toString();
	}

	public static void main(String[] args) throws ClientProtocolException, IOException {
		SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Map<String, String> params= new HashMap<String, String>();
		params.put("method", TaoBaoUrlConstans.NAME_TAOBAO_ITEM_COUPON_GET);
		params.put("sign_method", "hmac");
		params.put("app_key", "24712890");
		String date=f.format(new Date());
		params.put("timestamp", date);
		params.put("v", "2.0");
		params.put("format", "json");
		params.put("adzone_id", "165108088");
//		params.put("start_time", "2017-12-23 09:00:00");
//		params.put("end_time", "2017-12-23 12:00:00");
//		params.put("fields", "click_url,pic_url,reserve_price,zk_final_price,total_amount,sold_num,title,category_name,start_time,end_time");
		JSONObject result = JSONObject.parseObject(TaobaoAPISignUtil.getResult(params));
		JSONObject result1 = result.getJSONObject("tbk_dg_item_coupon_get_response");
		JSONObject result2  = result1.getJSONObject("results");
		JSONArray result3  = result2.getJSONArray("tbk_coupon");
		System.out.println(result1.toJSONString());
		System.exit(0);
	}
	

}
